<template>
    <div class="role_config_list">
        <el-tree ref="TreeRef" style="max-width: 600px" :data="state.data" node-key="id" show-checkbox
            :default-checked-keys="state.checked" >
            <template #default="{ node, data }">
                <div class="custom-tree-node">
                    <span>{{ node.label }}</span>
                </div>
            </template>
        </el-tree>
        <el-form-item style="margin-top:30px">
            <el-button type="primary" @click="submitForm()">
                保存
            </el-button>
            <el-button @click="cancel">取消</el-button>
        </el-form-item>
    </div>
</template>
<script setup>
import { ref, reactive, onMounted } from "vue"
import { permissionTree, config } from '@/api/system/role'
import { useRouter, useRoute } from 'vue-router'
import { ElNotification } from 'element-plus'

const route = useRoute()
const router = useRouter()
const TreeRef = ref(null)

const state = reactive({
    data: [],
    checked: []
})

const getTree = () => {
    permissionTree(route.params.id).then(data => {
        state.data = data
        addChecked(data)
    })
}

const addChecked = (list) => {
    if (!list || list.length == 0) {
        return true
    }
    let bool = true
    list.forEach(item => {
        let cBool = addChecked(item.children)
        if (item.checked === true && cBool) {
            state.checked.push(item.id)
        }else{
            bool = false
        }
    })
    return bool
}

const submitForm = () => {
    config(route.params.id, [...TreeRef.value.getCheckedKeys(), ...TreeRef.value.getHalfCheckedKeys()]).then(data => {
        ElNotification({
            title: '操作成功',
            message: '权限配置成功',
            type: 'success',
        })
        router.push('/role-list')
    })
}

const cancel = () => {
    router.push("/role-list")
}


onMounted(() => {
    getTree()
})
</script>
<style scoped lang="scss">
.role_config_list {
    height: 100%;

}
</style>
